package com.wandousoushu.jiusen.ui.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wandousoushu.jiusen.R;

public class CommonTitleBar extends RelativeLayout {
    private ImageView imageViewBack;
    private LinearLayout linearLayoutBack;
    private TextView textViewTitle;
    private Context mContext;

    public CommonTitleBar(Context context) {
        super(context);
    }

    public CommonTitleBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCommonTitleBar(context, attrs);
    }

    public CommonTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCommonTitleBar(context, attrs);
    }

    private void initCommonTitleBar(Context context, AttributeSet attrs) {
        this.mContext = context;
        LayoutInflater.from(context).inflate(R.layout.layout_title_bar, this);
        linearLayoutBack = findViewById(R.id.ll_common_bar_back);
        imageViewBack = (ImageView) findViewById(R.id.img_common_bar_back);
        textViewTitle = (TextView) findViewById(R.id.tv_common_bar_title);

        /**
         * title赋值
         */
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CommonTitleBar);
        String text = a.getString(R.styleable.CommonTitleBar_TitleBarTitle);
        if (text != null)
            textViewTitle.setText(text);
        textViewTitle.setTextColor(a.getColor(R.styleable.CommonTitleBar_TitleBarTextColor, Color.BLACK));
        /**
         * 返回键是否显示
         */
        boolean show = a.getBoolean(R.styleable.CommonTitleBar_TitleBarShowBack, true);
        imageViewBack.setVisibility(show ? VISIBLE : GONE);
        if (show) {
            imageViewBack.setImageDrawable(a.getDrawable(R.styleable.CommonTitleBar_TitleBarBackIcon));
        }
        /**
         * 背景设置
         */
        setBackgroundColor(a.getColor(R.styleable.CommonTitleBar_TitleBarBgColor, Color.WHITE));

        /**
         * 返回键监听
         */
        linearLayoutBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Activity activity = (Activity) mContext;
                    activity.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
